package api;

import model.Article;
import model.ArticleDao;
import model.User;
import view.HtmlGenerator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

//删除文章
public class DeleteArticleServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        //1.判断用户是否为登录状态
        HttpSession httpSession = req.getSession(false);
        if(httpSession == null ){
            //未登录
            String html = HtmlGenerator.getMessagePage("请先登录","login.html");
            resp.getWriter().write(html);
            return;
        }
        User user = (User)httpSession.getAttribute("user");
        //2.读取请求内容，获取要删除的文章id
        String articleIdStr = req.getParameter("articleId");
        if(articleIdStr == null || "".equals(articleIdStr)){
            String html = HtmlGenerator.getMessagePage("要删除的文章id有误","article");
            resp.getWriter().write(html);
            return;
        }

        //3.根据文章id判断用户是否是文章作者
        ArticleDao articleDao = new ArticleDao();
        Article article = articleDao.selectById(Integer.parseInt(articleIdStr));
        if(article.getUserId() != user.getUserId()){
            String html = HtmlGenerator.getMessagePage("您不是文章作者，无法删除!","article");
            resp.getWriter().write(html);
            return;
        }

        //4.删除文章
        articleDao.delete(Integer.parseInt(articleIdStr));
        //5.返回一个“删除成功”的页面
        String html = HtmlGenerator.getMessagePage("删除成功!","article");
        resp.getWriter().write(html);
    }
}
